package net.toby200.canalstoppages;

import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.cmd.LoadType;

import net.toby200.canalstoppages.model.AndroidRegistrationId;
import net.toby200.canalstoppages.model.Notice;
import net.toby200.canalstoppages.notify.Notifier;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.inject.Named;

import static com.googlecode.objectify.ObjectifyService.ofy;

@Api(name = "stoppages", version = "v1", 
	namespace = @ApiNamespace(ownerDomain = "canalstoppages.toby200.net", 
	ownerName = "canalstoppages.toby200.net", packagePath=""))
public class CanalStoppagesAPI {
	
	private static final Logger LOG = Logger.getLogger(CanalStoppagesAPI.class.getName());
	
	static {
		ObjectifyService.register(Notice.class);
        ObjectifyService.register(AndroidRegistrationId.class);
	}
	
	
	@ApiMethod(name = "getStoppages")
    public List<Notice> getNotices() {		
		LoadType<Notice> notices = ofy().load().type(Notice.class);
		if (notices == null) {
			LOG.log(Level.SEVERE, "No notices could be loaded");
			return new ArrayList<Notice>();
		}
		
		 List<Notice> arrNotices = notices.list();
		 
		 LOG.log(Level.INFO, "Notices loaded: " + arrNotices.size());
		 return arrNotices;
    }

    @ApiMethod(name = "sendTestNotification")
    public void sendTestNotification() {
        List<Notice> notices = getNotices();
        if (notices.size() > 0) {
            int index = (int)(Math.random() * notices.size());
            Notifier.sendNotification(notices.subList(index, index+1));
        }
    }
	
	@ApiMethod(
            name = "registerId",
            httpMethod = ApiMethod.HttpMethod.POST)
    public void setRegisterId(@Named("regId") String regId) {
        LOG.info("Registering android deviceId " + regId);
        ofy().save().entity(new AndroidRegistrationId(regId));
    }
}
